import XLSX from 'xlsx/dist/xlsx.core.min.js'

/**
 * 通过table导出excel文件
 * @param {*} columns {filed:label}
 * @param {*} tableData [{field1:'',field2:''}]
 * @param {*} exportName
 */
export function exportExcelByTable(columnConfig, tableData, exportName) {
  if (!columnConfig) {
    return
  }
  let aoaData = []
  let columnKeys = []
  let columnLabels = []
  for (const key in columnConfig) {
    columnKeys.push(key)
    columnLabels.push(columnConfig[key])
  }
  aoaData.push(columnLabels)
  if (tableData && Array.isArray(tableData)) {
    tableData.forEach(rItem => {
      let rowData = []
      columnKeys.forEach(cItem => {
        rowData.push(rItem[cItem.field || cItem] || '')
      })
      aoaData.push(rowData)
    })
  }

  let worksheet = XLSX.utils.aoa_to_sheet(aoaData)
  let workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet)
  XLSX.writeFile(workbook, `${exportName || '文件数据'}.xlsx`)
}
